package com.android.lovingpet.mine.setting.accountsecurity;

import android.util.Log;

import com.android.lovingpet.common.Back;
import com.android.lovingpet.util.HttpUtil;
import com.android.lovingpet.util.URLStore;
import com.android.lovingpet.util.Utility;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AuthModel {

    public void authEmail(String email, Back back) {
        Map<String, String> params = new HashMap<>(1);
        params.put("email", email);
        HttpUtil.postAsync(Utility.getJSessionId(), URLStore.USER_AUTH_EMAIL, params, defaultBack(back));
    }

    public void authIdCard(String name, String idCard, Back back) {
        Map<String, String> params = new HashMap<>(2);
        params.put("name", name);
        params.put("idCard", idCard);
        HttpUtil.postAsync(Utility.getJSessionId(), URLStore.IDCARD_AUTH, params, defaultBack(back));
    }

    /***
     * @param type 0是邮箱， 1是身份证
     */
    public void isAuth(int id, int type, Back back) {
        Map<String, String> params = new HashMap<>(2);
        params.put("id", id + "");
        params.put("type", type + "");
        HttpUtil.postAsync(Utility.getJSessionId(), URLStore.IDCARD_ISAUTH, params, defaultBack(back));
    }

    private Callback defaultBack(final Back back) {
         return new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                back.onFailure(HttpUtil.getFailureMeg());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject object = new JSONObject(response.body().string());
                    Log.d("验证", object.toString());
                    final int status = object.getInt("code");
                    if (status != 0) {
                        back.onFailure(HttpUtil.getCodeString(status));
                    } else {
                        back.onSuccess(null);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
